<?php

namespace TpAmis\Traits;

use EasyAdmin\tool\CommonTool;

trait RequestTrait
{
    /**
     * 是否关联查询
     * @var bool
     */
    protected $relationSearch = false;
    /**
     * 构建请求参数
     * @param array $excludeFields 忽略构建搜索的字段
     * @return array
     */
    protected function buildTableParames($excludeFields = [])
    {
        $get     = $this->request->get('', null, null);
        $page    = isset($get['page']) && ! empty($get['page']) ? $get['page'] : 1;
        $limit   = isset($get['limit']) && ! empty($get['limit']) ? $get['limit'] : 15;
        $filters = isset($get['filter']) && ! empty($get['filter']) ? $get['filter'] : '{}';
        $ops     = isset($get['op']) && ! empty($get['op']) ? $get['op'] : '{}';
        // json转数组
        $filters  = json_decode($filters, true);
        $ops      = json_decode($ops, true);
        $where    = [];
        $excludes = [];

        // 判断是否关联查询
        $tableName = CommonTool::humpToLine(lcfirst($this->model->getName()));

        foreach ($filters as $key => $val) {
            $val = trim($val);
            if (in_array($key, $excludeFields)) {
                $excludes[$key] = $val;
                continue;
            }
            $op = isset($ops[$key]) && ! empty($ops[$key]) ? $ops[$key] : '%*%';
            if ($this->relationSearch && count(explode('.', $key)) == 1) {
                $key = "{$tableName}.{$key}";
            }
            switch (strtolower($op)) {
                case '=':
                    $where[] = [$key, '=', $val];
                    break;
                case '%*%':
                    $where[] = [$key, 'LIKE', "%{$val}%"];
                    break;
                case '*%':
                    $where[] = [$key, 'LIKE', "{$val}%"];
                    break;
                case '%*':
                    $where[] = [$key, 'LIKE', "%{$val}"];
                    break;
                case 'in':
                    $where[] = [$key, 'find in set', $val];
                    break;
                case 'range':
                    [$beginTime, $endTime] = explode(' - ', $val);
                    if (in_array('create_time', explode('.', $key)) || in_array('update_time', explode('.', $key))) {
                        $where[] = [$key, '>=', strtotime($beginTime)];
                        $where[] = [$key, '<=', strtotime($endTime)];
                    } else {
                        $where[] = [$key, '>=', $beginTime];
                        $where[] = [$key, '<=', $endTime];
                    }
                    break;
                default:
                    $where[] = [$key, $op, "%{$val}"];
            }
        }
        return [$page, $limit, $where, $excludes];
    }
    /**
     * 处理请求数据为where条件
     * @param mixed $method
     * @return array
     */
    protected function Request($method = 'post')
    {
        $request = $this->request->$method();
        $where   = [];
        $page    = [];
        foreach ($request as $name => $value) {
            if ($value == '') {
                continue;
            }

            if (strpos($name, '|') !== false) {
                $name = str_replace('|', '.', $name);
            }


            $value = $this->isValidTimestampRange($name, $value);
            $value = $this->isValidDateRange($name, $value);

            switch ($name) {
                case 'page':
                    $page[$name] = (int) $value;
                    break;

                case 'list_rows':
                    $page[$name] = (int) $value;
                    break;

                default:
                    if (is_array($value)) {
                        $where[] = $value;
                    } else {

                        if ($value === false) {
                            $value = 0;
                        } elseif ($value === true) {
                            $value = 1;
                        }

                        $where[] = [$name, '=', $value];
                    }

                    break;
            }

        }

        return [$where, $page];
    }
    /**
     * 判断并获取逗号分隔时间戳字符串
     * @param mixed $name
     * @param mixed $input
     * @return mixed
     */
    function isValidTimestampRange($name, $input)
    {
        if (! is_string($input)) {
            return $input;
        }
        // 检查字符串是否包含逗号
        if (strpos($input, ',') === false) {
            return $input;
        }

        // 分割字符串
        list($timestamp1, $timestamp2) = explode(',', $input);

        // 去除可能的空格
        $timestamp1 = trim($timestamp1);
        $timestamp2 = trim($timestamp2);

        // 检查是否为数字
        if (! is_numeric($timestamp1) || ! is_numeric($timestamp2)) {
            return $input;
        }

        // 检查是否为有效的时间戳
        if (! is_int((int) $timestamp1) || ! is_int((int) $timestamp2)) {
            return $input;
        }

        // 检查时间戳范围是否合理（例如，第一个时间戳应小于第二个时间戳）
        if ((int) $timestamp1 >= (int) $timestamp2) {
            return $input;
        }

        return [$name, 'between', [$timestamp1, $timestamp2]];
    }

    /**
     * 判断并获取逗号分隔时间字符串
     * @param mixed $input
     * @return array
     */
    function isValidDateRange($name, $input)
    {
        if (! is_string($input)) {
            return $input;
        }
        // 检查字符串是否包含逗号
        if (strpos($input, ',') === false) {
            return $input;
        }

        // 分割字符串
        list($date1, $date2) = explode(',', $input);

        // 去除可能的空格
        $date1 = trim($date1);
        $date2 = trim($date2);

        // 验证日期格式是否为 YYYY-MM-DD
        if (! preg_match('/^\d{4}-\d{2}-\d{2}$/', $date1) || ! preg_match('/^\d{4}-\d{2}-\d{2}$/', $date2)) {
            return $input;
        }

        // 验证日期是否有效
        if (! checkdate(date('m', strtotime($date1)), date('d', strtotime($date1)), date('Y', strtotime($date1))) ||
            ! checkdate(date('m', strtotime($date2)), date('d', strtotime($date2)), date('Y', strtotime($date2)))) {
            return $input;
        }

        // 检查时间戳范围是否合理（例如，第一个日期应小于第二个日期）
        $timestamp1 = strtotime($date1);
        $timestamp2 = strtotime($date2);
        if ($timestamp1 >= $timestamp2) {
            return $input;
        }

        return [$name, 'between', [$date1, $date2]];
    }

}
